package com.droidclaimcustomer.activity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.droidclaimcustomer.R;
import com.droidclaimcustomer.bl.CustomerBl;
import com.droidclaimcustomer.bl.DroidClaimBlService;
import com.droidclaimcustomer.dto.ClaimRequestBlDto;
import com.droidclaimcustomer.dto.ClaimRequestResultBlDto;
import com.droidclaimcustomer.dto.UploadFileListDto;
import com.droidclaimcustomer.dto.UploadFileResultDto;
import com.droidclaimcustomer.helper.asyntask.ICompleteListener;
import com.droidclaimcustomer.model.ClaimInfoModel;
import com.droidclaimcustomer.model.ClaimRequestModel;
import com.droidclaimcustomer.model.StatusModel;

public class ClaimRequestActivity extends Activity implements ICompleteListener {

	private final int CAMERA_REQUEST_INTENT = 1;
	private TextView licensePlateNoTV;
	private TextView ownerNameTV;
	private TextView carDetailTV;
	private TextView customerMobileTV;
	private TextView statusTV;
	private ImageView accidentIV;
	private ImageButton imageCaptureBtn;
	private ImageButton sendBtn;
	private ImageButton cancelBtn;

	private ClaimRequestModel claimRequestModel;
	private StatusModel statusModel;

	private String taskAddClaimId;
	private String taskGetClaimInfoByRowId;
	private String taskUploadFileId;
	private ClaimRequestResultBlDto ClaimRequestResultdto;
	private List<File> fileList = new ArrayList<File>();
	Location location;
	Long recordId;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_claim_request);

		claimRequestModel = new ClaimRequestModel();
		statusModel = new StatusModel(this);
		// 1. after login get information form getExtra
		// object layout Item
		licensePlateNoTV = (TextView) findViewById(R.id.license_plate_no_textview);
		ownerNameTV = (TextView) findViewById(R.id.owner_name_textview);
		carDetailTV = (TextView) findViewById(R.id.car_detail_textview);
		customerMobileTV = (TextView) findViewById(R.id.customer_mobile_textview);
		statusTV = (TextView) findViewById(R.id.status_textview);
		accidentIV = (ImageView) findViewById(R.id.accident_imageview);
		imageCaptureBtn = (ImageButton) findViewById(R.id.image_btn);
		sendBtn = (ImageButton) findViewById(R.id.send_btn);
		cancelBtn = (ImageButton) findViewById(R.id.cancel_btn);

		// set button onClickListener
		imageCaptureBtn.setOnClickListener(onClickCaptureAccImg);
		sendBtn.setOnClickListener(onClickSendRequest);
		cancelBtn.setOnClickListener(onClickCancel);

		// get location
		Location loc = getCurrentLocationString();
		if (loc != null) {
			claimRequestModel.setLatitude(loc.getLatitude());
			claimRequestModel.setLongitude(loc.getLongitude());
			claimRequestModel.setLocation(getLocation(loc));
		}

		// claimInfo model GetIntentExtra
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			extrasToModel(extras);
			displayCustomerInfo();
		} else {
			Toast.makeText(this, "Customer info is null", Toast.LENGTH_LONG)
					.show();
		}

	}

	@Override
	protected void onResume() {
		super.onResume();
		displayCustomerInfo();
	}

	private void extrasToModel(Bundle extras) {
		claimRequestModel.setCarDetail(MainActivity.getCarDetail());
		claimRequestModel.setOwnerName(MainActivity.getOwnerName());
		claimRequestModel.setLicensePlate(MainActivity.getLicensePlate());
		claimRequestModel.setMobile(extras.getString("mobile"));
		claimRequestModel.setStatus("");
	}

	private void displayCustomerInfo() {
		// Display CustomerInfo
		if (claimRequestModel != null) {
			licensePlateNoTV.setText(claimRequestModel.getLicensePlate());
			ownerNameTV.setText(claimRequestModel.getOwnerName());
			carDetailTV.setText(claimRequestModel.getCarDetail());
			customerMobileTV.setText(claimRequestModel.getMobile());
			statusTV.setText(claimRequestModel.getStatus()); //
			accidentIV.setImageBitmap(claimRequestModel.getAccImg());
		}
	}

	private void clearCustomerInfo() {
		claimRequestModel.setStatus("");
		claimRequestModel.setAccImg(null);
		claimRequestModel.setAccImgPath("");
		displayCustomerInfo();
	}

	public View.OnClickListener onClickCancel = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			clearCustomerInfo();
			// setResult(ClaimRequestActivity.RESULT_CANCELED);
			// //sfinish();
		}
	};

	public View.OnClickListener onClickSendRequest = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			// ClaimRequestResultDto AddClaimRequest(ClaimRequestDto
			// ClaimRequest);
			DroidClaimBlService bl = new DroidClaimBlService(
					ClaimRequestActivity.this);
			CustomerBl customerBL = new CustomerBl(ClaimRequestActivity.this);
			Date date = new Date();

			if (claimRequestModel.getAccImg() != null) {
				/*
				 * Bitmap bmp =
				 * ((BitmapDrawable)accidentIV.getDrawable()).getBitmap();
				 * accidentImgStr = ImageString.toString(bmp); Uri imageUri =
				 * Uri.parse(accidentImgStr); accidentImgPath =
				 * imageUri.getPath(); //Image Path
				 */

				try {
					// set status
					claimRequestModel.setStatus(statusModel.getStatus(1)); // Requested
					// insert database
					ClaimInfoModel claimInfoModel = new ClaimInfoModel();
					claimInfoModel.setAccDate(date);
					claimInfoModel.setAccLocation(claimRequestModel
							.getLocation());
					claimInfoModel.setLatitude(claimRequestModel.getLatitude());
					claimInfoModel.setLongitude(claimRequestModel
							.getLongitude());
					claimInfoModel.setLicensePlateNo(claimRequestModel
							.getLicensePlate());
					claimInfoModel.setStatus(statusModel
							.getStatus(claimRequestModel.getStatus()));
					claimInfoModel.setUpdateDate(date);
					recordId = customerBL.addClaimInfo(claimInfoModel);

					if (recordId > 0) {
						// send request
						uploadFileList();
					}
					// display status
					displayCustomerInfo();
				} catch (Exception ex) {
					Toast.makeText(ClaimRequestActivity.this, "Error: " + ex,
							Toast.LENGTH_LONG).show();
				}
			} else {
				Toast.makeText(ClaimRequestActivity.this,
						"Please take a accident photo", Toast.LENGTH_LONG)
						.show();
			}
		}
	};

	public View.OnClickListener onClickCaptureAccImg = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			try {
				Intent intent = new Intent(
						android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
				startActivityForResult(intent, CAMERA_REQUEST_INTENT);
			} catch (Exception ex) {
				Toast.makeText(ClaimRequestActivity.this, "Error: " + ex,
						Toast.LENGTH_LONG).show();
			}
		}
	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == CAMERA_REQUEST_INTENT) {
			if (resultCode == Activity.RESULT_OK) {
				Bundle extras = data.getExtras();
				Bitmap bmp = (Bitmap) extras.get("data");

				String path = Environment.getExternalStorageDirectory()
						.toString();
				OutputStream fOut = null;
				File file = new File(path, "test.jpg");
				try {
					fOut = new FileOutputStream(file);
					bmp.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
					fOut.flush();
					fOut.close();
					fileList.add(file);
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				claimRequestModel.setAccImg(bmp);
				// Uri selectedImageUri = data.getData();
				// String accImgPath = selectedImageUri.getPath(); // Image Path
				// claimRequestModel.setAccImgPath(accImgPath);
				claimRequestModel.setAccImgPath(path + "/test.jpg");
				displayCustomerInfo();
			} else {
				Toast.makeText(this, "Intent result error", Toast.LENGTH_LONG)
						.show();
			}
		} else {
			Toast.makeText(this, "Request code error", Toast.LENGTH_LONG)
					.show();
		}

	}

	private Location getCurrentLocationString() {
		LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		List<String> providers = manager.getAllProviders();
		for (String provider : providers)
			if (manager.isProviderEnabled(provider) && provider.equals("gps")) {
				Location loc = manager.getLastKnownLocation(provider);
				return loc;
			}

		return null;
	}

	// get current location
	public String getLocation(Location loc) {
		String address = "";
		Geocoder geocoder = new Geocoder(getBaseContext(), Locale.getDefault());
		try {
			List<Address> addresses = geocoder.getFromLocation(
					loc.getLatitude(), loc.getLongitude(), 1);

			if (addresses != null && addresses.size() != 0) {
				Address returnedAddress = addresses.get(0);
				StringBuilder strReturnedAddress = new StringBuilder(
						"Address:\n");
				for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++) {
					strReturnedAddress
							.append(returnedAddress.getAddressLine(i)).append(
									"\n");
				}
				address = strReturnedAddress.toString();
			} else {
				DecimalFormat myFormatter = new DecimalFormat("###.##");
				address = myFormatter.format(loc.getLatitude()) + ","
						+ myFormatter.format(loc.getLongitude());
			}
		} catch (IOException e) {
			address = "";
		}

		return address;
	}

	private void uploadFileList() {
		UploadFileListDto dto = new UploadFileListDto();
		DroidClaimBlService bl = new DroidClaimBlService(
				ClaimRequestActivity.this);
		dto.setListFiles(fileList);
		taskUploadFileId = bl.UploadFile(dto);

	}

	private void sendToServer(String tempPathFile) {
		ClaimRequestBlDto dto = new ClaimRequestBlDto();
		DroidClaimBlService bl = new DroidClaimBlService(
				ClaimRequestActivity.this);
		dto.setSessionId(MainActivity.getSessionId());
		// dto.setAccImg(ImageString.toString(claimRequestModel.getAccImg()));
		dto.setAccImg(tempPathFile);
		dto.setLatitude(claimRequestModel.getLatitude());
		dto.setLongitude(claimRequestModel.getLongitude());
		dto.setLocation(claimRequestModel.getLocation()); // if location = null?
															// can sent or not
															// sent
		taskAddClaimId = bl.AddClaimRequest(dto);
	}

	@Override
	public void onTaskCompleteSuccess(String taskId, Object result) {
		// TODO Auto-generated method stub
		CustomerBl customerBL = new CustomerBl(this);

		if (taskId == taskAddClaimId) {
			ClaimRequestResultdto = (ClaimRequestResultBlDto) result;
			if (ClaimRequestResultdto.getClaimInfoId() != 0) {
				claimRequestModel.setId((long) ClaimRequestResultdto
						.getClaimInfoId());
				claimRequestModel.setStatus(statusModel.getStatus(2)); // Received
				// receive ClaimInfoID from Server and get ClaimInfo from DB for
				// update again
				/*
				 * Get Database by recordId;
				 */
				taskGetClaimInfoByRowId = customerBL
						.GetClaimInfoByRowId(recordId);
				displayCustomerInfo();
			} else {
				Toast.makeText(this, "Error", Toast.LENGTH_LONG).show();
			}
		} else if (taskId == taskGetClaimInfoByRowId) {
			ArrayList<ClaimInfoModel> valueArray = (ArrayList<ClaimInfoModel>) result;
			if (valueArray != null) {
				ClaimInfoModel dto = (ClaimInfoModel) valueArray.get(0);
				if (dto != null) {
					dto.setId(ClaimRequestResultdto.getClaimInfoId());
					updateClaiminfoDB(dto); // send current data for update db
				}
			}

		} else if (taskId == taskUploadFileId) {
			UploadFileResultDto dto = (UploadFileResultDto) result;
			if (dto.isResult()) {
				sendToServer(dto.getListFiles().get(0));
			}
		}
	}

	public boolean updateClaiminfoDB(ClaimInfoModel dto) {
		CustomerBl customerBL = new CustomerBl(this);
		Date date = new Date();
		// insert database
		ClaimInfoModel claimInfoModel = new ClaimInfoModel();
		// get current database and set all attribute in claimInfoModel
		claimInfoModel = dto;
		claimInfoModel.setId(claimRequestModel.getId());
		claimInfoModel.setStatus(statusModel.getStatus(claimRequestModel
				.getStatus()));
		claimInfoModel.setUpdateDate(date);
		boolean isUpdate = customerBL.updateClaiminfo(recordId, claimInfoModel);

		if (isUpdate) {
			displayCustomerInfo();
		}
		return true;
	}

	@Override
	public void onTaskFailed(String taskId, Exception cause) {
		// TODO Auto-generated method stub
		if (taskId == taskAddClaimId) {
			Toast.makeText(this, "Task Error" + taskId, Toast.LENGTH_LONG)
					.show();
		}
	}

}
